#include "symphonie.h"
#include "Smoothing.h"
//#include "treemodel.h"
#include <QTreeWidget>
#include <QGridLayout>
#include "Plot2D.h"
#include <qwt_plot.h>
#include <qwt_plot_marker.h>
#include <qwt_plot_curve.h>
#include <qwt_legend.h>
#include <qwt_data.h>
#include <qwt_text.h>
#include <qwt_math.h>
#include <qwt3d_surfaceplot.h>
#include <qwt3d_function.h>

#include "Plot3D.h"


Dataset *myDataset = new Dataset;
MainConfig *myConfig = new MainConfig;

QSignalMapper *signalMapper_ListView_remove;
QSignalMapper *signalMapper_ListView_SelectAll;
QSignalMapper *signalMapper_ListView_DeSelectAll;
QSignalMapper *signalMapper_ListView_Copy;






template < typename T >
        T **Allocate2DArray( int nRows, int nCols)
{
    //(step 1) allocate memory for array of elements of column
    T **ppi = new T*[nRows];

    //(step 2) allocate memory for array of elements of each row
    T *curPtr = new T [nRows * nCols];

    // Now point the pointers in the right place
    for( int i = 0; i < nRows; ++i)
    {
        *(ppi + i) = curPtr;
        curPtr += nCols;
    }
    return ppi;
}

template < typename T >
        void Free2DArray(T** Array)
{
    delete [] *Array;
    delete [] Array;
}

record_def::record_def()
{

}
record_def::~record_def()
{
}

int List_gamma_cmplx::convert_gamma_2_impedance()
{
    int i;
    QString temps;
    Single_gamma_cmplx temp, temp1, temp2;

    for(i=0;i<List_Gamma.count();i++){
        temp.val = Gamma2Z(List_Gamma.at(i).val, 50);

        temp.Label = List_Gamma.at(i).Label;
        temp.Label.replace(QString("Grec"),QString("ImpZ"));
        List_Impedance.append(temp);
        temps.clear();
        QTextStream(&temps) << temp.val.dat[0]<< " "<<temp.val.dat[1];
    }
    return 0;
}

int List_gamma_cmplx::convert_gamma_2_polar()
{
    int i;
    double arg, mag;
    Single_gamma_cmplx temp, temp1, temp2;

    for(i=0;i<List_Gamma.count();i++){
        arg = gsl_complex_arg(List_Gamma.at(i).val);
        arg = arg/M_PI *180;
        mag = gsl_complex_abs(List_Gamma.at(i).val);
        GSL_SET_COMPLEX(&temp.val, mag,arg);
        temp.Label = List_Gamma.at(i).Label;
        temp.Label.replace(QString("Grec"),QString("Gpol"));
        List_Gamma_polar.append(temp);
    }
    return 0;
}
int LP_rec::Add_compression_infos()
{
    int k,l;
    QString temp;
    float temp_float;

    swp_rec _swp_rec;

    _swp_rec.swp.clear();
    _swp_rec.Label.clear();

    k=0;
    int max_indx;
    float max=0;

    temp = LP.at(0)->Label;
    while(!temp.contains("Gt")&& k < LP.count())
    {
        k++;
        temp = LP.at(k)->Label;
    }
    //copy the vector

    if(temp.contains("Gt")){

        {
            //_swp_rec.swp = All_Freq_data.at(0)._Single_Freq_data.at(0)->LP;
            max=LP.at(k)->swp.at(0);
            max_indx =0;
            for(l=0;l<LP.at(k)->swp.count();l++){
                temp_float = LP.at(k)->swp.at(l);
                if(temp_float > max){
                    max = LP.at(k)->swp.at(l);
                    max_indx = l;
                }
            }

            for(l=0;l<LP.at(k)->swp.count();l++){
                if(l<=max_indx)
                    _swp_rec.swp.append(0);
                else{
                    temp_float = LP.at(k)->swp.at(l);
                    _swp_rec.swp.append(max - temp_float);
                }
            }

            _swp_rec.Label = "Compression";
            LP.append(new swp_rec(_swp_rec));
        }

    }
    return 0;
}

int LP_rec::compute_AMPM()
{
    int k,l;
    QString temp;
    float temp_float;

    swp_rec _swp_rec;

    _swp_rec.swp.clear();
    _swp_rec.Label.clear();

    k=0;
    float max=0;

    temp = LP.at(0)->Label;
    while(!temp.contains("trans_phase")&& k < LP.count()-1)
    {
        k++;
        temp = LP.at(k)->Label;
    }
    //copy the vector

    if(temp.contains("trans_phase")){
        //_swp_rec.swp = All_Freq_data.at(0)._Single_Freq_data.at(0)->LP;
        max=LP.at(k)->swp.at(0);
        for(l=0;l<LP.at(k)->swp.count();l++){

            temp_float = LP.at(k)->swp.at(l)-max;
            if(temp_float >0)
                temp_float=temp_float-360;

            _swp_rec.swp.append(temp_float);

        }

        _swp_rec.Label = "AMPM";
        LP.append(new swp_rec(_swp_rec));

    }

    return 0;
}

int record_def::FillTreemodel()
{
    QString temp, temp2, temp3;
    int i, j, k, l;

    model = new TreeModel();

    QList<QVariant> rootData;
    QList<int> indentations;
    int position = 0;
    indentations << 0;


    for(i=0;i< All_Freq_data.at(0)->spl.at(0)->LP.count();i++)
    {
        rootData << All_Freq_data.at(0)->spl.at(0)->LP.at(i)->Label;
    }
    model->rootItem = new TreeItem(rootData);

    QList<TreeItem*> parents;
    parents << model->rootItem;


    int number = 0;

    QList<QVariant> columnData;
    QVariant temp_Qvariant;
    for (i = 0; i < All_Freq_data.count(); i++)
    {
        //first identation with Freq info
        columnData.clear();
        {
            temp_Qvariant = All_Freq_data.at(i)->spl.at(0)->LP.at(0)->swp.at(0);
            columnData << temp_Qvariant;
            for(k=0;k< All_Freq_data.at(i)->spl.at(0)->LP.count();k++)
                columnData << "";
            position =0;

            {
                if (position > indentations.last()) {
                    // The last child of the current parent is now the new parent
                    // unless the current parent has no children.

                    if (parents.last()->childCount() > 0) {
                        parents << parents.last()->child(parents.last()->childCount()-1);
                        indentations << position;
                    }
                } else {
                    while (position < indentations.last() && parents.count() > 0) {
                        parents.pop_back();
                        indentations.pop_back();
                    }
                }
                // Append a new item to the current parent's list of children.
                parents.last()->appendChild(new TreeItem(columnData, parents.last()));
            }

        }

        for (j = 0; j < All_Freq_data.at(i)->spl.count(); j++)
        {
            //second identation with Gamma info
            columnData.clear();
            {
                temp.clear();
                for(l=0;l<All_Freq_data.at(i)->spl.at(j)->gammas.at(0).List_Gamma.count();l++){
                    temp2 = All_Freq_data.at(i)->spl.at(j)->gammas.at(0).List_Gamma.at(l).Label;
                    temp3.sprintf("= %1.3f +j*%1.3f", GSL_REAL(All_Freq_data.at(i)->spl.at(j)->gammas.at(0).List_Gamma.at(l).val),GSL_IMAG(All_Freq_data.at(i)->spl.at(j)->gammas.at(0).List_Gamma.at(l).val));
                    temp = temp+" "+temp2+" "+temp3+" ";
                }
                columnData<< temp.toAscii();

                for(k=2;k<All_Freq_data.at(i)->spl.at(j)->LP.count()+2;k++)
                    columnData << "";
                position =1;

                {
                    if (position > indentations.last()) {
                        // The last child of the current parent is now the new parent
                        // unless the current parent has no children.

                        if (parents.last()->childCount() > 0) {
                            parents << parents.last()->child(parents.last()->childCount()-1);
                            indentations << position;
                        }
                    } else {
                        while (position < indentations.last() && parents.count() > 0) {
                            parents.pop_back();
                            indentations.pop_back();
                        }
                    }
                    // Append a new item to the current parent's list of children.
                    parents.last()->appendChild(new TreeItem(columnData, parents.last()));
                }

            }
            //second A identation with Gamma info
            columnData.clear();
            {
                temp.clear();
                for(l=0;l<All_Freq_data.at(i)->spl.at(j)->gammas.at(0).List_Gamma_polar.count();l++){
                    temp2 = All_Freq_data.at(i)->spl.at(j)->gammas.at(0).List_Gamma_polar.at(l).Label;
                    temp3.sprintf("= %1.3f/_%1.3f", GSL_REAL(All_Freq_data.at(i)->spl.at(j)->gammas.at(0).List_Gamma_polar.at(l).val),GSL_IMAG(All_Freq_data.at(i)->spl.at(j)->gammas.at(0).List_Gamma_polar.at(l).val));
                    temp = temp+" "+temp2+" "+temp3+" ";
                }
                columnData<< temp.toAscii();

                for(k=2;k<All_Freq_data.at(i)->spl.at(j)->LP.count()+2;k++)
                    columnData << "";
                position =1;

                {
                    if (position > indentations.last()) {
                        // The last child of the current parent is now the new parent
                        // unless the current parent has no children.

                        if (parents.last()->childCount() > 0) {
                            parents << parents.last()->child(parents.last()->childCount()-1);
                            indentations << position;
                        }
                    } else {
                        while (position < indentations.last() && parents.count() > 0) {
                            parents.pop_back();
                            indentations.pop_back();
                        }
                    }
                    // Append a new item to the current parent's list of children.
                    parents.last()->appendChild(new TreeItem(columnData, parents.last()));
                }

            }
            //second B identation with Gamma info
            columnData.clear();
            {   temp.clear();
                for(l=0;l<All_Freq_data.at(i)->spl.at(j)->gammas.at(0).List_Impedance.count();l++){
                    temp2 = All_Freq_data.at(i)->spl.at(j)->gammas.at(0).List_Impedance.at(l).Label;
                    temp3.sprintf("= %1.3f +j*%1.3f", GSL_REAL(All_Freq_data.at(i)->spl.at(j)->gammas.at(0).List_Impedance.at(l).val),GSL_IMAG(All_Freq_data.at(i)->spl.at(j)->gammas.at(0).List_Impedance.at(l).val));
                    temp = temp+" "+temp2+" "+temp3+" ";
                }
                columnData<< temp.toAscii();



                for(k=2;k<All_Freq_data.at(i)->spl.at(j)->LP.count()+2;k++)
                    columnData << "";
                position =1;

                {
                    if (position > indentations.last()) {
                        // The last child of the current parent is now the new parent
                        // unless the current parent has no children.

                        if (parents.last()->childCount() > 0) {
                            parents << parents.last()->child(parents.last()->childCount()-1);
                            indentations << position;
                        }
                    } else {
                        while (position < indentations.last() && parents.count() > 0) {
                            parents.pop_back();
                            indentations.pop_back();
                        }
                    }
                    // Append a new item to the current parent's list of children.
                    parents.last()->appendChild(new TreeItem(columnData, parents.last()));
                }

            }

            //third identation with SWP
            {
                position=2;
                //columnData.clear();
                for (k = 0; k < All_Freq_data.at(i)->spl.at(j)->LP.at(0)->swp.count(); k++)
                {
                    //columnData.clear();
                    QList<QVariant> columnData;
                    for (l = 0; l < All_Freq_data.at(i)->spl.at(j)->LP.count(); l++)
                    {
                        temp_Qvariant = All_Freq_data.at(i)->spl.at(j)->LP.at(l)->swp.at(k);

                        columnData << temp_Qvariant;
                        number++;
                    }
                    {
                        if (position > indentations.last()) {
                            // The last child of the current parent is now the new parent
                            // unless the current parent has no children.

                            if (parents.last()->childCount() > 0) {
                                parents << parents.last()->child(parents.last()->childCount()-1);
                                indentations << position;
                            }
                        } else {
                            while (position < indentations.last() && parents.count() > 0) {
                                parents.pop_back();
                                indentations.pop_back();
                            }
                        }
                        // Append a new item to the current parent's list of children.
                        parents.last()->appendChild(new TreeItem(columnData, parents.last()));
                    }
                    // position++;
                }

            }
        }
    }
    return 0;
}
Symphonie::Symphonie(QWidget *parent, Qt::WFlags flags)
        : QDialog(parent, flags)
{

    ui.setupUi(this);

    setWindowFlags(windowFlags() | Qt::WindowMinMaxButtonsHint);

    setAttribute(Qt::WA_Moved, false);
    {
        test3D = new Plot_3D(ui.SPL_plot3D_widget);
        test3D->setupWorkaround(ui.SPL_plot3D_widget);
        QGridLayout *grid = new QGridLayout( test3D->SPL_Plot_3D_frame );

        test3D->col_ = 0;
        test3D->legend_ = false;
        test3D->redrawWait = 50;
        test3D->activeCoordSystem = test3D->None;

        test3D->dataWidget = new SurfacePlot(test3D->SPL_Plot_3D_frame);
        grid->addWidget( test3D->dataWidget, 0, 0 );
        connect( test3D->coord, SIGNAL( triggered( QAction* ) ),test3D, SLOT( pickCoordSystem( QAction* ) ) ) ;

        connect( test3D->plotstyle, SIGNAL( triggered( QAction* ) ), test3D, SLOT( pickPlotStyle( QAction* ) ) ) ;
        connect( test3D->floorstyle, SIGNAL( triggered( QAction* ) ),test3D, SLOT( pickFloorStyle( QAction* ) ) ) ;

        connect( test3D->left, SIGNAL( toggled( bool ) ), test3D, SLOT( setLeftGrid(bool ) ) );
        connect( test3D->right, SIGNAL( toggled( bool ) ), test3D, SLOT( setRightGrid( bool ) ) );
        connect( test3D->ceil, SIGNAL( toggled( bool ) ), test3D, SLOT( setCeilGrid( bool ) ) );
        connect( test3D->floor, SIGNAL( toggled( bool ) ), test3D, SLOT( setFloorGrid( bool ) ) );
        connect( test3D->back, SIGNAL( toggled( bool ) ), test3D, SLOT( setBackGrid( bool ) ) );
        connect( test3D->front, SIGNAL( toggled( bool ) ), test3D, SLOT( setFrontGrid( bool ) ) );

        connect(test3D->functionCB, SIGNAL(activated(const QString&)), test3D, SLOT(createFunction(const QString&)));
        connect(test3D->psurfaceCB, SIGNAL(activated(const QString&)), test3D, SLOT(createPSurface(const QString&)));
        connect(test3D->normals, SIGNAL( toggled(bool) ), test3D, SLOT( showNormals(bool)));

        test3D->setStandardView();

        test3D->dataWidget->coordinates()->setLineSmooth(true);
        test3D->dataWidget->coordinates()->setGridLinesColor(RGBA(0.35,0.35,0.35,1));
        test3D->dataWidget->enableMouse(true);
    }

    // init mapper for context menu from List_View
    signalMapper_ListView_remove = new QSignalMapper(this);
    connect(signalMapper_ListView_remove, SIGNAL(mapped(const QString &)), this, SLOT(ListView_Remove(const QString &)));

    signalMapper_ListView_Copy = new QSignalMapper(this);
    connect(signalMapper_ListView_Copy, SIGNAL(mapped(const QString &)), this, SLOT(ListView_Copy(const QString &)));

    signalMapper_ListView_SelectAll = new QSignalMapper(this);
    connect(signalMapper_ListView_SelectAll, SIGNAL(mapped(const QString &)), this, SLOT(ListView_SelectAll(const QString &)));

    signalMapper_ListView_DeSelectAll = new QSignalMapper(this);
    connect(signalMapper_ListView_DeSelectAll, SIGNAL(mapped(const QString &)), this, SLOT(ListView_DeSelectAll(const QString &)));

    //init user context menu
    ui.selected_file->setContextMenuPolicy(Qt::CustomContextMenu); //CustomContextMenu
    connect(ui.selected_file, SIGNAL(customContextMenuRequested(const QPoint &)),SLOT(showContextMenuFor_SelectedFile(const QPoint &)));


    ui.SPL_exract_results->setContextMenuPolicy(Qt::CustomContextMenu);
    connect(ui.SPL_exract_results, SIGNAL(customContextMenuRequested(const QPoint &)),SLOT(showContextMenuFor_SPL_extract_result(const QPoint &)));

    ui.List_file_in_database->setContextMenuPolicy(Qt::CustomContextMenu);
    connect(ui.List_file_in_database, SIGNAL(customContextMenuRequested(const QPoint &)),SLOT(showContextMenuFor_List_file_in_database(const QPoint &)));

    ui.Main_disp_message->setContextMenuPolicy(Qt::CustomContextMenu);
    connect(ui.Main_disp_message, SIGNAL(customContextMenuRequested(const QPoint &)),SLOT(showContextMenuFor_Main_disp_message(const QPoint &)));


    connect(ui.Select_skin, SIGNAL(clicked()),this,SLOT(Select_skin_f()));
    connect(ui.SaveAs_wks, SIGNAL(clicked()),this,SLOT(SaveAs_workspace()));
    connect(ui.Save_wks, SIGNAL(clicked()),this,SLOT(Save_workspace()));
    connect(ui.Open_wks, SIGNAL(clicked()),this,SLOT(Open_workspace()));
    connect(ui.New_wks, SIGNAL(clicked()),this,SLOT(New_workspace()));




    ui.ui_SelectMenu->setCurrentIndex(0);
    ui.ui_StackedTabs->setCurrentIndex(0);

    ui.loading_file_progress_bar->setVisible( FALSE );
    ui.loading_file_progress_bar->setEnabled( FALSE );
    ui.loading_file_progress_bar_2->setVisible( FALSE );
    ui.loading_file_progress_bar_2->setEnabled( FALSE );
    ui.progressBar_process->setVisible(FALSE);
    ui.progressBar_process->setEnabled(FALSE);

    ui.styleComboBox->addItems(QStyleFactory::keys());
    QLabel *styleLabel = new QLabel(tr("&Style:"));
    styleLabel->setBuddy(ui.styleComboBox);

    connect(ui.styleComboBox, SIGNAL(activated(const QString &)),
            this, SLOT(changeStyle(const QString &)));

    QString mytext;
    mytext = QApplication::applicationName() + " " + QApplication::applicationVersion();

    ui.pathDeformRendererEx->setText(mytext);
    ui.pathDeformRendererEx->setPreferImage(false);

    //gsl_complex *Gammas = (gsl_complex*)malloc(sizeof(gsl_complex));
    qwtPlot = new Plot_2D(ui.SPL_widget_2); //
    qwtPlot->InitPlot(ui.SPL_widget_2);
    qwtPlot->setTitle("my test");

    qwtPlot2 = new Plot_2D(ui.SPL_widget_3); //
    qwtPlot2->InitPlot(ui.SPL_widget_3);
    qwtPlot2->setTitle("my test3");

    qwtPlot3 = new Plot_2D(ui.SPL_widget_4); //
    qwtPlot3->InitPlot(ui.SPL_widget_4);
    qwtPlot3->setTitle("my test4");

    qwtPlot4 = new Plot_2D(ui.SPL_widget_5); //
    qwtPlot4->InitPlot(ui.SPL_widget_5);
    qwtPlot4->setTitle("my test5");



}
void Symphonie::on_AboutQt_clicked(){
    QApplication::aboutQt();
}

Symphonie::~Symphonie()
{

}

void Symphonie::on_ui_SelectMenu_currentChanged(int value)
{
    int i=0;

    int indx = ui.ui_SelectMenu->currentIndex();
    ui.ui_StackedTabs->setCurrentIndex(indx);
    switch(indx){
    case 0:
        break;
    case 2:
        ui.List_file_in_database->clear();
        for(i=0;i<myDataset->record.count();i++)
            ui.List_file_in_database->addItem(myDataset->record.at(i)->Shortfilename);

        break;
    default:
        break;
    }
}

int Symphonie::on_SPL_process_saveas_clicked()
{
    QList<QListWidgetItem *>  mylist;
    QString openFiles;
    QString openFilesPath;
    QString temp;

    QString y = "\\";
    QFileDialog::Options options;

    options |= QFileDialog::DontUseNativeDialog;
    QString selectedFilter;
    QString files = QFileDialog::getSaveFileName(this, tr("Save File"),"",tr("Data file (*.csv)"),&selectedFilter,options);
    QFile file(files);
    if (!file.open(QIODevice::Append | QIODevice::Text))
    {
        Add_message_to_status_windows("failed to open the file, please check the file");
        return 1;
    }

    QTextStream out(&file);
    //copy comment to file
    temp = ui.SPL_exract_comment->toPlainText();
    out <<temp.toAscii()<< endl;

    ui.SPL_exract_results->selectAll();
    mylist << ui.SPL_exract_results->selectedItems();
    for(int i=0;i<mylist.count();i++)
    {
        temp = mylist.at(i)->text().toAscii();
        temp.replace(QString("\t"),QString(","));
        out << temp.toAscii()<< endl;
    }
    file.close();
    return 0;

}
void Symphonie::on_SPL_compute_optim_clicked()
{
    QList<QListWidgetItem *>  exract_keep;
    QList<QListWidgetItem *>  exract_optim;
    QString temp;
    QList<QString> paramlist,paramlist2;
    QFont serifFont("Times", 12, 75);
    QListWidgetItem *item = new QListWidgetItem;


    int i;
    // on optim Compression PxdB compute max Paramlist

    exract_keep << ui.SPL_exract_keep->selectedItems();
    exract_optim << ui.SPL_exract_optim->selectedItems();


    paramlist.clear();
    paramlist2.clear();

    for(i=0;i<exract_optim.count();i++)
        paramlist.append(exract_optim.at(i)->text());
    for(i=0;i<exract_keep.count();i++)
        paramlist2.append(exract_keep.at(i)->text());

    // save default config
    myConfig->SPL.Optim_paramlist=paramlist;
    myConfig->SPL.Optim_paramlist2=paramlist2;
    myConfig->SPL.Optim_target = ui.SPL_optim_target->text();
    myConfig->SPL.Optim_Computed_on=ui.SPL_optims_computed_on->currentText().toAscii();

    //ui.SPL_exract_results->clear();
    if(Compute_optimums_at_X_on_parm(ui.progressBar_process,ui.SPL_optims_computed_on->currentText().toAscii(),ui.SPL_optim_target->text().toFloat(),myDataset->active_dataset, myDataset)==0)
    {
        QList<QString> res = Find_Max_from_optimums(ui.progressBar_process,paramlist,paramlist2,myDataset);

        temp.clear();
        QTextStream(&temp) << myDataset->record.at(myDataset->active_dataset)->Shortfilename;
        item->setText(temp);
        item->setFont(serifFont);
        item->setTextColor(Qt::red);
        ui.SPL_exract_results->addItem(item);

        temp.clear();
        item = new QListWidgetItem;
        QTextStream(&temp) << "Optimums computed on " << ui.SPL_optims_computed_on->currentText().toAscii()<<"= "<<ui.SPL_optim_target->text().toFloat();
        item->setText(temp);
        item->setFont(serifFont);
        ui.SPL_exract_results->addItem(item);

        for(i=0;i<res.count();i++)
        {
            ui.SPL_exract_results->addItem(res.at(i));
        }
    }
}


void Symphonie::on_Add_file_clicked()
{
    QString openFiles;
    QString openFilesPath;
    //QListWidgetItem *item = new QListWidgetItem(openFiles);
    QString y = "\\";
    QFileDialog::Options options;
    options |= QFileDialog::DontUseNativeDialog;
    QString selectedFilter;
    QStringList files = QFileDialog::getOpenFileNames(
            this, tr("Select Files to be added to your workspace"),
            openFilesPath,
            tr("Maury File (*.* *.spl *.swp *.lp);;All Files (*);;Maury Sweep File (*.spl);;Maury Sweep File (*.swp)"),
            &selectedFilter,
            options);

    if (files.count())
    {
        for(int i=0;i<files.count();i++)
        {
            openFiles = files[i];
            if (openFiles.contains(".spl") || openFiles.contains(".lp"))
                ui.selected_file->addItem(openFiles);
            else if (openFiles.contains(".swp"))
                ui.selected_file->addItem(openFiles);
        }
        ui.selected_file->setCurrentRow(0);
    }
}

void Symphonie::on_Workspace_active_clicked()
{
    QString mytext, message;


    QList<QListWidgetItem *>  SelectedList;
    //retrieve all selected files
    SelectedList << ui.selected_file->selectedItems();
    ui.loading_file_progress_bar_2->setVisible( TRUE );
    ui.loading_file_progress_bar_2->setEnabled( TRUE );
    if(SelectedList.count()>0){
        mytext = "Loading file(s) in memory, please wait !!";
        ui.loading_file_progress_bar_2->setFormat(mytext);
        ui.loading_file_progress_bar_2->setRange(0,SelectedList.count());
        ui.loading_file_progress_bar_2->setValue(0);
        for(int i =0 ; i < SelectedList.count() ; i++)
        {
            mytext = SelectedList.at(i)->text();
            if(!mytext.isEmpty())
            {
                if(mytext.contains(".spl"))
                {
                    record_def *Dataset = new record_def;
                    Dataset->filename = mytext;
                    ui.workspace_activefile_label->setText(mytext);
                    // load file in memory
                    Dataset->filetype="spl";
                    message.clear();
                    if( !Read_spl_file(Dataset, &message,ui.loading_file_progress_bar))
                    {
                        ui.Workspace_infos_file->clear();
                        //Add_message_to_status_windows(message.toAscii());
                        Add_Workspace_file_infos(ui.Workspace_infos_file, Dataset);
                        Dataset->FillTreemodel();
                        myDataset->record.append(Dataset);
                    }
                    Add_message_to_status_windows(message.toAscii());

                }
                if(mytext.contains(".lp"))
                {
                    record_def *Dataset = new record_def;
                    Dataset->filename = mytext;
                    ui.workspace_activefile_label->setText(mytext);
                    // load file in memory
                    Dataset->filetype="lp";
                    if( !Read_lp_file(Dataset, &message,ui.loading_file_progress_bar))
                    {
                        Add_Workspace_file_infos(ui.Workspace_infos_file, Dataset);
                        myDataset->record.append(Dataset);
                        //Update_process_windows(Dataset);
                    }
                }
                if(mytext.contains(".swp"))
                {

                    record_def *Dataset = new record_def;
                    Dataset->filename = mytext;
                    ui.workspace_activefile_label->setText(mytext);
                    
                    // load file in memory
                    Dataset->filetype="swp";
                    message.clear();

                    if( !Read_swp_file(Dataset, &message,ui.loading_file_progress_bar))
                    {

                        ui.Workspace_infos_file->clear();
                        Add_Workspace_file_infos(ui.Workspace_infos_file, Dataset);
                        //Dataset->FillTreemodel();
                        myDataset->record.append(Dataset);

                    }

                    Add_message_to_status_windows(message.toAscii());

                }
                ui.loading_file_progress_bar_2->setValue(i+1);
                QCoreApplication::processEvents();
            }

        }
        mytext = "All file(s) loaded !!";
        ui.loading_file_progress_bar_2->setFormat(mytext);
        ui.loading_file_progress_bar_2->setVisible( TRUE );
        ui.loading_file_progress_bar->setVisible( FALSE );
    }
}

void Symphonie::Add_message_to_status_windows_Qstring(QString msg)
{
    ui.Main_disp_message->addItem(msg);
}
void Symphonie::Add_message_to_status_windows_QstringList(QStringList msg)
{
    ui.Main_disp_message->addItems(msg);
}
void Symphonie::Add_message_to_status_windows(QString msg)
{
    ui.Main_disp_message->addItem(msg);
}

template<class T> void Symphonie::Add_Workspace_file_infos(QListWidget *target,T *data)//record_def
{
    QString text, temp;
    QFont serifFont("Times", 10, 75);
    int i;
    target->clear();

    if(data->filetype.contains("spl"))
    {
        text = "Filename:";
        QListWidgetItem *item = new QListWidgetItem;
        item->setText(text);
        item->setFont(serifFont);
        target->addItem(item);
        text = "\t" + data->Shortfilename;
        target->addItem(text);

        text = "Label:";
        item = new QListWidgetItem;
        item->setText(text);
        item->setFont(serifFont);
        target->addItem(item);
        text = "\t" + data->Label;
        target->addItem(text);

        text = "Date:";
        item = new QListWidgetItem;
        item->setText(text);
        item->setFont(serifFont);
        target->addItem(item);

        text ="\t"+ data->Date;
        target->addItem(text);

        text = "Frequency available in GHz:";
        item = new QListWidgetItem;
        item->setText(text);
        item->setFont(serifFont);
        target->addItem(item);
        text.clear();
        for(i=0;i < data->FreqVariables.count();i++){
            temp.sprintf("%f", data->FreqVariables.at(i).freq);
            text.append("\t" + temp.toAscii());
        }
        target->addItem(text);

        text = "Variables:";
        item = new QListWidgetItem;
        item->setText(text);
        item->setFont(serifFont);
        target->addItem(item);
        text.clear();
        for(i=0;i<data->FreqVariables.at(0).freqvar.count();i++){
            text.append("\t"+data->FreqVariables.at(0).freqvar.at(i).Label+"("+data->FreqVariables.at(0).freqvar.at(i).Units+")");
        }
        target->addItem(text);

        text = "Parameters:";
        item = new QListWidgetItem;
        item->setText(text);
        item->setFont(serifFont);
        target->addItem(item);

        for(i=0;i<data->Headers_list.count();i++)
        {
            text = data->Headers_list.at(i);
            if(!text.contains("valid"))
                target->addItem("\t"+ text);
        }
        return;
    }
    if(data->filetype.contains("lp"))
    {
        text = "Filename:";
        QListWidgetItem *item = new QListWidgetItem;
        item->setText(text);
        item->setFont(serifFont);
        target->addItem(item);
        text = "\t" + data->Shortfilename;
        target->addItem(text);

        text = "Label:";
        item = new QListWidgetItem;
        item->setText(text);
        item->setFont(serifFont);
        target->addItem(item);
        text = "\t" + data->Label;
        target->addItem(text);

        text = "Date:";
        item = new QListWidgetItem;
        item->setText(text);
        item->setFont(serifFont);
        target->addItem(item);

        text ="\t"+ data->Date;
        target->addItem(text);

        text = "Frequency available in GHz:";
        item = new QListWidgetItem;
        item->setText(text);
        item->setFont(serifFont);
        target->addItem(item);
        text.clear();
        for(i=0;i < data->FreqVariables.count();i++){
            QTextStream(&text) << "\t" << data->FreqVariables.at(i).freq;
        }
        target->addItem(text);
        text = "Parameters:";
        item = new QListWidgetItem;
        item->setText(text);
        item->setFont(serifFont);
        target->addItem(item);
        /*
        for(i=0;i<data->data_nFreq.at(0).at(0).count();i++)
        {
      //      text = data->data_nFreq.at(0).at(0).at(i);
            //text = "test";
            if(!text.contains("valid"))
                target->addItem("\t"+ text);
        }
*/
        return;
    }
    if(data->filetype.contains("swp")) {
        text = "Filename:";
        QListWidgetItem *item = new QListWidgetItem;
        item->setText(text);
        item->setFont(serifFont);
        target->addItem(item);
        text = "\t" + data->Shortfilename;
        target->addItem(text);

        text = "Label:";
        item = new QListWidgetItem;
        item->setText(text);
        item->setFont(serifFont);
        target->addItem(item);
        text = "\t" + data->Label;
        target->addItem(text);

        text = "Date:";
        item = new QListWidgetItem;
        item->setText(text);
        item->setFont(serifFont);
        target->addItem(item);

        text ="\t"+ data->Date;
        target->addItem(text);

        text = "Frequency available in GHz:";
        item = new QListWidgetItem;
        item->setText(text);
        item->setFont(serifFont);
        target->addItem(item);
        text.clear();
        for(i=0;i < data->FreqVariables.count();i++){
            temp.sprintf("%f", data->FreqVariables.at(i).freq);
            text.append("\t" + temp.toAscii());
        }
        target->addItem(text);


        text = "Parameters:";
        item = new QListWidgetItem;
        item->setText(text);
        item->setFont(serifFont);
        target->addItem(item);

        for(i=0;i<data->Headers_list.count();i++)
        {
            text = data->Headers_list.at(i);
            if(!text.contains("valid"))
                target->addItem("\t"+ text);
        }

        return;
    }
    text = "no informations available";
    target->addItem(text);

}

template<class T> void Symphonie::Add_file_infos(QTreeView *target,T *data) //record_def
{
    if(data->filetype.contains("spl")){
        target->setModel(data->model);
    }
}
template<class T> void  Symphonie::Update_process_windows(T *data)
{
    if(data->filetype.contains("spl")){
        ui.ui_StackedTabs-> setCurrentIndex(2);
        ui.tabSPL-> setCurrentIndex(0);
    }
}


void Symphonie::contextMenuEvent(QContextMenuEvent * event ){

    /* QMenu* contextMenu = new QMenu( this );
    contextMenu->setTitle("GlView");
    contextMenu->addAction( "&Save Image", this, SLOT(saveImage()), Qt::CTRL+Qt::Key_S );
    contextMenu->exec( QCursor::pos() );
    delete contextMenu;
    */
}

void Symphonie::showContextMenuFor_SelectedFile(const QPoint &pos)
{

    QMenu contextMenu(tr("Context menu"), this);
    //  contextMenu.setStyleSheet(QString::fromUtf8("color: rgb(255, 255, 255);"));

    QAction *action = new QAction(QIcon(":/trolltech/styles/commonstyle/images/standardbutton-clear-32.png"),tr("Remove from the list"), this);
    action->setShortcut(QKeySequence("ctrl+x"));
    signalMapper_ListView_remove->setMapping(action, QString("SelectedFile"));
    connect(action, SIGNAL(triggered()),signalMapper_ListView_remove, SLOT (map()));
    contextMenu.addAction(action);

    action = new QAction(tr("Select All"), this);
    action->setShortcut(QKeySequence("ctrl+a"));
    signalMapper_ListView_SelectAll->setMapping(action, QString("SelectedFile"));
    connect(action, SIGNAL(triggered()),signalMapper_ListView_SelectAll, SLOT (map()));
    contextMenu.addAction(action);

    action = new QAction(tr("DeSelect All"), this);
    action->setShortcut(QKeySequence("ctrl+q"));
    signalMapper_ListView_DeSelectAll->setMapping(action, QString("SelectedFile"));
    connect(action, SIGNAL(triggered()),signalMapper_ListView_DeSelectAll, SLOT (map()));
    contextMenu.addAction(action);

    contextMenu.exec(mapToGlobal(pos));
}

void Symphonie::showContextMenuFor_SPL_extract_result(const QPoint &pos)
{
    QMenu contextMenu(tr("Context menu"), this);
    //  contextMenu.setStyleSheet(QString::fromUtf8("color: rgb(255, 255, 255);"));

    QAction *action = new QAction(QIcon(":/trolltech/styles/commonstyle/images/standardbutton-clear-32.png"),tr("Remove from the list"), this);
    action->setShortcut(QKeySequence("ctrl+x"));
    contextMenu.addAction(action);
    signalMapper_ListView_remove->setMapping(action, QString("ResultOptim"));
    connect(action, SIGNAL(triggered()),signalMapper_ListView_remove, SLOT (map()));

    /*action = new QAction(tr("Copy to clipboard"), this);
    action->setShortcut(QKeySequence("ctrl+c"));
    contextMenu.addAction(action);
    signalMapper_ListView_Copy->setMapping(action, QString("ResultOptim"));
    connect(action, SIGNAL(triggered()),signalMapper_ListView_Copy, SLOT (map()));
*/

    action = new QAction(tr("Select All"), this);
    action->setShortcut(QKeySequence("ctrl+a"));
    signalMapper_ListView_SelectAll->setMapping(action, QString("ResultOptim"));
    connect(action, SIGNAL(triggered()),signalMapper_ListView_SelectAll, SLOT (map()));
    contextMenu.addAction(action);

    action = new QAction(tr("DeSelect All"), this);
    action->setShortcut(QKeySequence("ctrl+q"));
    signalMapper_ListView_DeSelectAll->setMapping(action, QString("ResultOptim"));
    connect(action, SIGNAL(triggered()),signalMapper_ListView_DeSelectAll, SLOT (map()));
    contextMenu.addAction(action);

    contextMenu.exec(mapToGlobal(pos));
}


void Symphonie::showContextMenuFor_Main_disp_message(const QPoint &pos)
{
    QMenu contextMenu(tr("Context menu"), this);
    //  contextMenu.setStyleSheet(QString::fromUtf8("color: rgb(255, 255, 255);"));

    QAction *action = new QAction(QIcon(":/trolltech/styles/commonstyle/images/standardbutton-clear-32.png"),tr("Remove from the list"), this);
    action->setShortcut(QKeySequence("ctrl+x"));
    contextMenu.addAction(action);
    signalMapper_ListView_remove->setMapping(action, QString("Main_disp_message"));
    connect(action, SIGNAL(triggered()),signalMapper_ListView_remove, SLOT (map()));


    action = new QAction(tr("Select All"), this);
    action->setShortcut(QKeySequence("ctrl+a"));
    signalMapper_ListView_SelectAll->setMapping(action, QString("Main_disp_message"));
    connect(action, SIGNAL(triggered()),signalMapper_ListView_SelectAll, SLOT (map()));
    contextMenu.addAction(action);

    action = new QAction(tr("DeSelect All"), this);
    action->setShortcut(QKeySequence("ctrl+q"));
    signalMapper_ListView_DeSelectAll->setMapping(action, QString("Main_disp_message"));
    connect(action, SIGNAL(triggered()),signalMapper_ListView_DeSelectAll, SLOT (map()));
    contextMenu.addAction(action);

    contextMenu.exec(mapToGlobal(pos));
}
void Symphonie::showContextMenuFor_List_file_in_database(const QPoint &pos)
{
    QMenu contextMenu(tr("Context menu"), this);
    //  contextMenu.setStyleSheet(QString::fromUtf8("color: rgb(255, 255, 255);"));

    QAction *action = new QAction(QIcon(":/trolltech/styles/commonstyle/images/standardbutton-clear-32.png"),tr("Remove from the list"), this);
    action->setShortcut(QKeySequence("ctrl+x"));
    contextMenu.addAction(action);
    signalMapper_ListView_remove->setMapping(action, QString("List_file_in_database"));
    connect(action, SIGNAL(triggered()),signalMapper_ListView_remove, SLOT (map()));

    /*
    action = new QAction(tr("Select All"), this);
    action->setShortcut(QKeySequence("ctrl+a"));
    signalMapper_ListView_SelectAll->setMapping(action, QString("List_file_in_database"));
    connect(action, SIGNAL(triggered()),signalMapper_ListView_SelectAll, SLOT (map()));
    contextMenu.addAction(action);

    action = new QAction(tr("DeSelect All"), this);
    action->setShortcut(QKeySequence("ctrl+q"));
    signalMapper_ListView_DeSelectAll->setMapping(action, QString("List_file_in_database"));
    connect(action, SIGNAL(triggered()),signalMapper_ListView_DeSelectAll, SLOT (map()));
    contextMenu.addAction(action);
*/
    contextMenu.exec(mapToGlobal(pos));
}
void Symphonie::ListView_Remove(const QString &text){
    int i;
    if(text.contains("SelectedFile"))
    {
        qDeleteAll(ui.selected_file->selectedItems());
    }
    if(text.contains("ResultOptim"))
    {
        qDeleteAll(ui.SPL_exract_results->selectedItems());
    }
    if(text.contains("List_file_in_database"))
    {
        QString name = ui.List_file_in_database->currentItem()->text();
        for(i=0; i<myDataset->record.count();i++)
            if(myDataset->record.at(i)->Shortfilename.contains(name))
            {
            myDataset->record.removeAt(i);
            qDeleteAll(ui.List_file_in_database->selectedItems());
        }
    }

    if(text.contains("Main_disp_message"))
    {
        qDeleteAll(ui.Main_disp_message->selectedItems());
    }



}
void Symphonie::ListView_DeSelectAll(const QString &text)
{
    if(text.contains("SelectedFile"))
    {
        ui.selected_file->setCurrentRow(0);
    }
    if(text.contains("ResultOptim"))
    {
        ui.SPL_exract_results->setCurrentRow(0);
    }
    if(text.contains("Main_disp_message"))
    {
        ui.Main_disp_message->setCurrentRow(0);
    }
}
void Symphonie::ListView_SelectAll(const QString &text)
{
    if(text.contains("SelectedFile"))
    {
        ui.selected_file->selectAll();
    }
    if(text.contains("ResultOptim"))
    {
        ui.SPL_exract_results->selectAll();
    }
    if(text.contains("Main_disp_message"))
    {
        ui.Main_disp_message->selectAll();
    }

}

void Symphonie::ListView_Copy(const QString &text)
{
    if(text.contains("SelectedFile"))
    {
        ui.selected_file->selectAll();
    }
    if(text.contains("ResultOptim"))
    {
        ui.SPL_exract_results->selectAll();
    }
    if(text.contains("Main_disp_message"))
    {
        ui.Main_disp_message->selectAll();
    }

}
void Symphonie::on_List_file_in_database_itemPressed()
{
    //retrieve all selected files
    int i,j;
    QString text, text1, temp;
    QList<QString> paramlist, paramlist2;
    QStringList Listtext;
    //vtkActor *imageActor = vtkActor::New();
    QString name = ui.List_file_in_database->currentItem()->text();
    //QwtPlot *plot;

    //Qwt3D::SurfacePlot *mySurfacePlot;

    for(i=0; i<myDataset->record.count();i++)
        if(myDataset->record.at(i)->Shortfilename.contains(name))
        {myDataset->active_dataset=i;
            break;
        }

    if(myDataset->record.at(i)->filetype.contains("spl") || myDataset->record.at(i)->filetype.contains("swp")){
        ui.ui_StackedTabs->setCurrentIndex(2);
        ui.tabSPL->setCurrentIndex(0);
        temp.clear();
        Add_Workspace_file_infos(ui.List_SPL_Infos_dataset,myDataset->record.at(myDataset->active_dataset));
        //ui.SPL_exract_results->clear();
        ui.SPL_exract_optim->clear();
        ui.SPL_exract_keep->clear();
        ui.SPL_optims_computed_on->clear();
        ui.SPL_combo_1->blockSignals(true);
        ui.SPL_slider_1->blockSignals(true);
        ui.SPL_combo_1->clear();
        ui.SPL_Plot1_X->clear();
        ui.SPL_Plot1_X_2->clear();
        ui.SPL_Plot1_X_3->clear();
        ui.SPL_Plot1_X_4->clear();

        ui.SPL_Plot1_Y1->clear();
        ui.SPL_Plot1_Y1_2->clear();
        ui.SPL_Plot1_Y1_3->clear();
        ui.SPL_Plot1_Y1_4->clear();

        ui.SPL_Plot1_Y2->clear();
        ui.SPL_Plot1_Y2_2->clear();
        ui.SPL_Plot1_Y2_3->clear();
        ui.SPL_Plot1_Y2_4->clear();

        if(myDataset->record.at(i)->filetype.contains("swp")) ui.treeView1->reset();
        else Add_file_infos(ui.treeView1,myDataset->record.at(myDataset->active_dataset));
        //ui.SPL_exract_comment->setPlainText(myDataset->record.at(i)->Shortfilename);
        for(j=0;j<myDataset->record.at(myDataset->active_dataset)->All_Freq_data.at(0)->spl.at(0)->LP.count();j++){
            text = myDataset->record.at(myDataset->active_dataset)->All_Freq_data.at(0)->spl.at(0)->LP.at(j)->Label;
            if(!text.contains("Freq"))
            {
                ui.SPL_exract_keep->addItem(text.toAscii());
                ui.SPL_exract_optim->addItem(text.toAscii());
                ui.SPL_optims_computed_on->addItem(text.toAscii());
                ui.SPL_Plot1_X->addItem(text.toAscii());
                ui.SPL_Plot1_X_2->addItem(text.toAscii());
                ui.SPL_Plot1_X_3->addItem(text.toAscii());
                ui.SPL_Plot1_X_4->addItem(text.toAscii());

                ui.SPL_Plot1_Y1->addItem(text.toAscii());
                ui.SPL_Plot1_Y1_2->addItem(text.toAscii());
                ui.SPL_Plot1_Y1_3->addItem(text.toAscii());
                ui.SPL_Plot1_Y1_4->addItem(text.toAscii());

                ui.SPL_Plot1_Y2->addItem(text.toAscii());
                ui.SPL_Plot1_Y2_2->addItem(text.toAscii());
                ui.SPL_Plot1_Y2_3->addItem(text.toAscii());
                ui.SPL_Plot1_Y2_4->addItem(text.toAscii());
            }
        }
        text="none";
        ui.SPL_Plot1_Y1->addItem(text.toAscii());
        ui.SPL_Plot1_Y1_2->addItem(text.toAscii());
        ui.SPL_Plot1_Y1_3->addItem(text.toAscii());
        ui.SPL_Plot1_Y1_4->addItem(text.toAscii());

        ui.SPL_Plot1_Y2->addItem(text.toAscii());
        ui.SPL_Plot1_Y2_2->addItem(text.toAscii());
        ui.SPL_Plot1_Y2_3->addItem(text.toAscii());
        ui.SPL_Plot1_Y2_4->addItem(text.toAscii());

        for(j=0;j<myDataset->record.at(i)->FreqVariables.count();j++)
        {
            text.clear();
            temp.clear();
            QTextStream(&text) << myDataset->record.at(myDataset->active_dataset)->FreqVariables.at(j).freq;
            ui.SPL_combo_1->addItem(text.toAscii());

        }
        on_SPL_update_plot_clicked();

        ui.SPL_combo_1->blockSignals(false);
        on_SPL_combo_1_currentIndexChanged();
        ui.SPL_slider_1->blockSignals(false);
        on_SPL_slider_1_valueChanged();

        // set default value
        ui.SPL_optim_target->setText(myConfig->SPL.Optim_target.toAscii());
        ui.SPL_optims_computed_on->setCurrentIndex(ui.SPL_optims_computed_on->findText(myConfig->SPL.Optim_Computed_on));

        for(i=0;i< ui.SPL_exract_keep->count();i++)
        {
            for(j=0;j< myConfig->SPL.Optim_paramlist2.count();j++)
                if(ui.SPL_exract_keep->item(i)->text().contains(myConfig->SPL.Optim_paramlist2[j]))
                    ui.SPL_exract_keep->item(i)->setSelected(true);
            for(j=0;j< myConfig->SPL.Optim_paramlist.count();j++)
                if(ui.SPL_exract_optim->item(i)->text().contains(myConfig->SPL.Optim_paramlist[j]))
                    ui.SPL_exract_optim->item(i)->setSelected(true);
        }
        return;

    }
    if(myDataset->record.at(i)->filetype.contains("lp"))
    {

        return;
    }
}



void swp_rec::compute_min_max()
{
    min = swp.first();
    max = swp.first();
    for(int i=0;i<swp.count();i++){
        if(swp.at(i) < min)
            min = swp.at(i);
        if(swp.at(i) > max)
            max = swp.at(i);
    }
}


void Symphonie::on_SPL_combo_1_currentIndexChanged()
{
    QString text;

    int i = myDataset->active_dataset;
    text = ui.SPL_combo_1->currentText().toAscii();
    int nb_load =  find_index_Freq_and_Vars("Load",text.toFloat(), myDataset->record.at(i)->FreqVariables);
    nb_load = nb_load-1;
    ui.SPL_slider_1->setRange(0,nb_load);
    ui.SPL_slider_1->setValue(0);
}

void Symphonie::on_SPL_slider_1_valueChanged()
{
    QList<float> x, y1, y2;
    QString text, text1, temp;
    int i = myDataset->active_dataset;
    int j = ui.SPL_slider_1->value();

    text1 = ui.SPL_combo_1->currentText().toAscii();
    int k = find_index_Freq_and_Vars("freq",text1.toFloat(), myDataset->record.at(i)->FreqVariables);
    myDataset->active_freq = k;
    myDataset->active_load = j;

    if(myDataset->record.at(i)->All_Freq_data.at(k)->spl.at(j)->valid ==0)
        ui.SPL_valid->setChecked(false);
    else ui.SPL_valid->setChecked(true);

    Plot_SPL_curve(qwtPlot,i, j, k, qwtPlot->Xlabel.toAscii(), qwtPlot->Y1label.toAscii(), qwtPlot->Y2label.toAscii());
    Plot_SPL_curve(qwtPlot2,i, j, k, qwtPlot2->Xlabel.toAscii(), qwtPlot2->Y1label.toAscii(), qwtPlot2->Y2label.toAscii());
    Plot_SPL_curve(qwtPlot3,i, j, k, qwtPlot3->Xlabel.toAscii(), qwtPlot3->Y1label.toAscii(), qwtPlot3->Y2label.toAscii());
    Plot_SPL_curve(qwtPlot4,i, j, k, qwtPlot4->Xlabel.toAscii(), qwtPlot4->Y1label.toAscii(), qwtPlot4->Y2label.toAscii());
    text.clear();
    ui.SPL_list_impd->clear();

    for(int l=0;l<myDataset->record.at(i)->All_Freq_data.at(k)->spl.at(j)->gammas.at(0).List_Impedance.count();l++)
    {
        text.clear();
        text1.clear();
        text1.sprintf("%2.2f +j* %2.2f", GSL_REAL(myDataset->record.at(i)->All_Freq_data.at(k)->spl.at(j)->gammas.at(0).List_Impedance.at(l).val),GSL_IMAG(myDataset->record.at(i)->All_Freq_data.at(k)->spl.at(j)->gammas.at(0).List_Impedance.at(l).val));
        QTextStream(&text)<< myDataset->record.at(i)->All_Freq_data.at(k)->spl.at(j)->gammas.at(0).List_Impedance.at(l).Label <<"= " << text1;
        ui.SPL_list_impd->addItem(text.toAscii());
    }
    ui.SPL_list_impd->addItem(" ");

    for(int l=0;l<myDataset->record.at(i)->All_Freq_data.at(k)->spl.at(j)->gammas.at(0).List_Gamma_polar.count();l++)
    {
        text.clear();
        text1.clear();
        text1.sprintf("%2.2f /_ %2.2f", GSL_REAL(myDataset->record.at(i)->All_Freq_data.at(k)->spl.at(j)->gammas.at(0).List_Gamma_polar.at(l).val),GSL_IMAG(myDataset->record.at(i)->All_Freq_data.at(k)->spl.at(j)->gammas.at(0).List_Gamma_polar.at(l).val));
        QTextStream(&text)<< myDataset->record.at(i)->All_Freq_data.at(k)->spl.at(j)->gammas.at(0).List_Gamma_polar.at(l).Label <<"= " << text1;
        ui.SPL_list_impd->addItem(text.toAscii());
    }
}


void Symphonie::on_SPL_valid_stateChanged()
{
    QString temp;
    temp.clear();
    if(ui.SPL_valid->isChecked()== true)
        myDataset->record[myDataset->active_dataset]->All_Freq_data[myDataset->active_freq]->spl[myDataset->active_load]->valid =1;
    else myDataset->record[myDataset->active_dataset]->All_Freq_data[myDataset->active_freq]->spl[myDataset->active_load]->valid =0;
}

void Symphonie::Plot_SPL_curve(Plot_2D  *qwtPlot,int i, int j, int k, QString Xlabel, QString Y1label, QString Y2label)
{
    QList<float> x, y1, y2;
    QString text, text1, temp;
    QFont serifFont("Times", 10, 10);

    QwtText qwtXlabel(Xlabel.toAscii());
    QwtText qwtY1label(Y1label.toAscii());
    QwtText qwtY2label(Y2label.toAscii());
    qwtXlabel.setFont(serifFont);
    qwtY1label.setFont(serifFont);
    qwtY2label.setFont(serifFont);

    qwtPlot->clear();

    x = myDataset->record.at(i)->All_Freq_data.at(k)->spl.at(j)->LP.at(find_index_QListString(Xlabel, myDataset->record.at(i)->All_Freq_data.at(k)->spl.at(j)->LP))->swp;

    if(!Y1label.contains("none"))
        y1 = myDataset->record.at(i)->All_Freq_data.at(k)->spl.at(j)->LP.at(find_index_QListString(Y1label, myDataset->record.at(i)->All_Freq_data.at(k)->spl.at(j)->LP))->swp;
    if(!Y2label.contains("none"))
        y2 = myDataset->record.at(i)->All_Freq_data.at(k)->spl.at(j)->LP.at(find_index_QListString(Y2label, myDataset->record.at(i)->All_Freq_data.at(k)->spl.at(j)->LP))->swp;

    qwtPlot->setAxisTitle(QwtPlot::yLeft, qwtY1label);
    qwtPlot->setAxisTitle(QwtPlot::yRight, qwtY2label);
    qwtPlot->setAxisTitle(QwtPlot::xBottom, qwtXlabel);

    qwtPlot->setAxisFont(QwtPlot::yLeft, serifFont);
    qwtPlot->setAxisFont(QwtPlot::yRight, serifFont);
    qwtPlot->setAxisFont(QwtPlot::xBottom, serifFont);
    qwtPlot->setTitle("");
    qwtPlot->setFont(serifFont);
    qwtPlot->setplot(x,y1,y2,Y1label, Y2label);
}

void Symphonie::on_SPL_update_plot_clicked()
{
    qwtPlot->Xlabel = ui.SPL_Plot1_X->currentText().toAscii();
    qwtPlot->Y1label = ui.SPL_Plot1_Y1->currentText().toAscii();
    qwtPlot->Y2label = ui.SPL_Plot1_Y2->currentText().toAscii();

    qwtPlot2->Xlabel = ui.SPL_Plot1_X_2->currentText().toAscii();
    qwtPlot2->Y1label = ui.SPL_Plot1_Y1_2->currentText().toAscii();
    qwtPlot2->Y2label = ui.SPL_Plot1_Y2_2->currentText().toAscii();

    qwtPlot3->Xlabel = ui.SPL_Plot1_X_3->currentText().toAscii();
    qwtPlot3->Y1label = ui.SPL_Plot1_Y1_3->currentText().toAscii();
    qwtPlot3->Y2label = ui.SPL_Plot1_Y2_3->currentText().toAscii();

    qwtPlot4->Xlabel = ui.SPL_Plot1_X_4->currentText().toAscii();
    qwtPlot4->Y1label = ui.SPL_Plot1_Y1_4->currentText().toAscii();
    qwtPlot4->Y2label = ui.SPL_Plot1_Y2_4->currentText().toAscii();
    on_SPL_slider_1_valueChanged();
}

void Symphonie::Select_skin_f()
{
    QString mystyle;

    QString openFiles;
    QString openFilesPath;
    QString temp;

    QString y = "\\";
    QFileDialog::Options options;

    options |= QFileDialog::DontUseNativeDialog;
    QString selectedFilter;
    QString files = QFileDialog::getOpenFileName(this, tr("Skin File"),"",tr("Skin file (*.qss)"),&selectedFilter,options);
    QFile file(files);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        Add_message_to_status_windows("failed to open this Skin file, please check the file");
        return ;
    }


    QTextStream stream( &file );
    mystyle = stream.readAll();
    file.close();
    this->setStyleSheet(mystyle);
    this->update();
    this->repaint();
}

void Symphonie::changeStyle(const QString &styleName)
{
    QApplication::setStyle(QStyleFactory::create(styleName));
}

void Symphonie::SaveAs_workspace()
{
    QString openFiles, message;
    QString openFilesPath;

    QString y = "\\";
    QFileDialog::Options options;

    options |= QFileDialog::DontUseNativeDialog;
    QString selectedFilter;
    QString files = QFileDialog::getSaveFileName(this, tr("Symphonie Workspace"),"",tr("Symphonie Workspace file (*.wks)"),&selectedFilter,options);
    if(!files.contains(".wks")) files.append(".wks");
    myConfig->Current_WorkSpace = files;
    Save_workspace_f(files, &message, ui, myConfig);
    Add_message_to_status_windows(message.toAscii());
}

void Symphonie::Save_workspace()
{
    QString name = myConfig->Current_WorkSpace.toAscii();
    QString message;
    Save_workspace_f(name, &message, ui, myConfig);
    Add_message_to_status_windows(message.toAscii());
}


void Symphonie::Open_workspace()
{
    QString openFiles, message;
    QString openFilesPath;
    QList<QListWidgetItem *>  mylist;
    QString temp, line;
    QString y = "\\";
    QFileDialog::Options options;
    options |= QFileDialog::DontUseNativeDialog;
    QString selectedFilter;
    QString files = QFileDialog::getOpenFileName(this, tr("Symphonie Workspace"),"",tr("Symphonie Workspace file (*.wks)"),&selectedFilter,options);

    myConfig->Current_WorkSpace = files;
    Open_workspace_f(files, &message, ui, myConfig);
    Add_message_to_status_windows(message.toAscii());
}

void Symphonie::New_workspace()
{
    ui.selected_file->clear();
    ui.SPL_exract_results->clear();
    ui.Workspace_infos_file->clear();
    ui.Ledit_Current_Workspace->clear();
    ui.workspace_activefile_label->clear();
    ui.tabSPL->setCurrentIndex(0);
    ui.loading_file_progress_bar_2->setFormat("select file(s)");
    ui.loading_file_progress_bar_2->setValue(0);
    ui.List_file_in_database->clear();
    while(myDataset->record.count()>0)
    {
        myDataset->record.removeAt(0);
    }

    /*
    QString name = myConfig->Current_WorkSpace.toAscii();
    QString message;
    Save_workspace_f(name, &message, ui, myConfig);
    Add_message_to_status_windows(message.toAscii());
    */
}
